package com.jinfang.bankpractice.service;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jinfang.bankpractice.mapper.QuesbankMapper;
import com.jinfang.bankpractice.model.Quesbank;

@Service
public class QuesbankService {
	private static Logger log = LoggerFactory.getLogger(QuesbankService.class);

	@Resource
	private QuesbankMapper quesbankMapper;
	
	@Resource
	private RecordService recordService;
	
	

	/**
	 * 练习模式<br>
	 * 已经做过的题将不出再出现
	 * @param amount
	 * @param course
	 * @param userid
	 * @return　
	 */
	public Set<Quesbank> practice(int amount, int course, long userid) {		
		Set<Long> doneids=recordService.getDone(userid, course);
		List<Quesbank> all=quesbankMapper.queryAll(course);
		
		if(doneids==null||doneids.isEmpty())
			return getRand(amount, all);
		List<Quesbank> availablelist= all.stream().filter(q->!doneids.contains(q.getId())).collect(Collectors.toList());		
		log.info("可用的题量={}",availablelist.size());
		return getRand(amount, availablelist);
	}


	/**
	 * 从列表中随机取出amount个问题
	 * ＠author foolifish007
	 * @param amount
	 * @param availablelist
	 * @return
	 */
	private Set<Quesbank> getRand(int amount,final List<Quesbank> availablelist) {
		if( amount >= availablelist.size()){
			log.info("数量不足，返回所有的．total={},amount={}", availablelist.size(), amount);
			return availablelist.stream().collect(Collectors.toSet());
		}
		else {
			Set<Quesbank> result = new HashSet<Quesbank>();
			for(int i=0;i<amount;i++){				
				int locat = new Random().nextInt(availablelist.size()-i);
				result.add(availablelist.get(locat));
				// swap
				Quesbank tmp = availablelist.get(locat);
				availablelist.set(locat, availablelist.get(availablelist.size() -i-1));
				availablelist.set(availablelist.size() - i-1, tmp);			
			}
			return result;
		}
	}
	
	
	
	/**
	 * 模拟测试
	 * @param amount
	 * @param course
	 * @return
	 */
	public Set<Quesbank> test(int amount, int course) {
		List<Quesbank> all=quesbankMapper.queryAll(course);
		return getRand(amount, all);
	}
	
	/**
	 * 错题专练
	 * @param amount
	 * @param course
	 * @param userid
	 * @return
	 */
	public Set<Quesbank> error(int amount,int course,long userid){
		Set<Long> errors=recordService.getError(userid, course);
		log.info("error ids={}",errors);
		if(errors==null||errors.isEmpty())
			return Collections.emptySet();
		List<Quesbank> all=quesbankMapper.getQuesbankByids(errors.stream().collect(Collectors.toList()));
		return getRand(amount, all);
	}
	
	/*public static void main(String[] ar){
		log.info(new Random().nextInt(2)+"");
		log.info(new Random().nextInt(2)+"");
		log.info(new Random().nextInt(2)+"");
		log.info(new Random().nextInt(1)+"");
	}*/

}
